package com.xwli.javase.example;

import com.xwli.javase.thread.impl.MyRunnable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @program: springcloud
 * @description:
 *  Executor 管理多个异步任务的执行，而无需程序员显式地管理线程的生命周期。
 *  这里的异步是指多个任务的执行互不干扰，不需要进行同步操作
 * @author: xwli
 * @create: 2022-03-12 15:14
 **/
public class ExecutorExample {
    public static void main(String[] args) {
        testFixedThreadPool();
        System.out.println("开始执行main线程的任务！！！");
    }

    /**
    * @description: CachedThreadPool：一个任务创建一个线程；
    * @params: []
    * @return: void
    * @author: xwli
    * @date: 2022/3/12 15:15
    */
    private static void testCachedThreadPool(){
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {
            executorService.execute(new MyRunnable());
        }
        executorService.shutdown();
    }

    /**
    * @description: FixedThreadPool：所有任务只能使用固定大小的线程；
    * @params: []
    * @return: void
    * @author: xwli
    * @date: 2022/3/12 15:19
    */
    private static void testFixedThreadPool(){
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        for (int i = 0; i < 5; i++) {
            executorService.execute(new MyRunnable());
        }
        executorService.shutdown();
    }
}
